package com.qx.ddx.httprequest;

import android.content.Context;
import android.util.Log;

import com.qx.ddx.nohttplibrary.NoHttp;
import com.qx.ddx.nohttplibrary.Request;
import com.qx.ddx.util.Constants;
import com.qx.ddx.util.nohttp.CallServer;
import com.qx.ddx.util.nohttp.HttpArrayInterface;
import com.qx.ddx.util.nohttp.HttpListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2016/4/30.
 */
public class CallRequest {
    private HttpArrayInterface mc;

    public CallRequest(HttpArrayInterface mc) {
        this.mc = mc;
    }

    public void Connect(Context context, String token, String id) {
        String Parameter = "token=" + token + "&id=" + id;
        Request<JSONObject> request = NoHttp.createJsonObjectRequest(Constants.Call_Request + Parameter);
        Log.i("CallRequest", "连接访问: " + Constants.Call_Request + Parameter);
        request.setCancelSign(Constants.Call_Request_id);
        CallServer.getRequestInstance().add(context, Constants.Call_Request_id, request, objectListener, true, false);
    }

    private HttpListener objectListener = new HttpListener() {
        @Override
        public void onSucceed(int what, Object jsonObject, boolean isParseData, String message) {
            if (isParseData)
                parseData(what, (JSONObject) jsonObject);
        }

        public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis, String message) {
            mc.getData(what, null, false, message);
        }
    };

    private void parseData(int what, JSONObject jsonObject) {
        List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
        try {
            JSONArray array = jsonObject.getJSONArray("data");
            for (int i = 0; i < array.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject oj = (JSONObject) array.get(i);
                map.put("created_time", oj.getString("created_time"));
                map.put("updated_time", oj.getString("updated_time"));
                map.put("name", oj.getString("name"));
                map.put("creator_id", oj.getString("creator_id"));
                map.put("updater_id", oj.getString("updater_id"));
                map.put("id", oj.getString("id"));
                data.add(map);
            }
            mc.getData(what, data, true, "");
        } catch (org.json.JSONException e) {
            Log.e("JSONException", "CallRequest: " + e.toString());
            mc.getData(what, null, false, "解析数据错误");
        }

    }
}
